package com.yugao.fintech.antelope.statistic.handler;

import com.alibaba.fastjson2.JSONObject;
import com.yugao.fintech.antelope.statistic.api.constant.StatisticCons;
import com.yugao.fintech.antelope.statistic.api.model.mq.StatisticMQ;
import com.yugao.fintech.antelope.statistic.model.entity.StatAccess;
import com.yugao.fintech.antelope.statistic.service.StatAccessService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 统计访问日志日志
 */
@Slf4j
@Component
public class StatisticAccessHandler extends AbstractStatisticHandler {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private StatAccessService statAccessService;

    @Override
    public String type() {
        return StatisticCons.Type.ACCESS;
    }

    @Override
    public void process(StatisticMQ.Payload req) {
        JSONObject data = req.getData();
        Boolean isFail = data.getBoolean("isFail");
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String cacheKey = String.format(StatisticCons.ACCESS_KEY, req.getTenantId(), date, !isFail);
        stringRedisTemplate.boundValueOps(cacheKey).increment(1);
        stringRedisTemplate.boundValueOps(cacheKey).expire(24, TimeUnit.HOURS);
    }

    @Override
    public void execTask(Long tenantId) {
        log.info("stat access task, tenantId: {}", tenantId);
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String accessFailKey = String.format(StatisticCons.ACCESS_KEY, tenantId, date, false);
        String accessSuccessKey = String.format(StatisticCons.ACCESS_KEY, tenantId, date, true);
        String accessFailCount = stringRedisTemplate.opsForValue().get(accessFailKey);
        String accessSuccessCount = stringRedisTemplate.opsForValue().get(accessSuccessKey);
        log.info("access ===> failCount: {}, successCount: {}", accessFailCount, accessSuccessCount);

        StatAccess stat = new StatAccess().setStatDate(LocalDate.now())
                .setFailCount(StringUtils.isEmpty(accessFailCount) ? null : Long.parseLong(accessFailCount))
                .setSuccessCount(StringUtils.isEmpty(accessSuccessCount) ? null : Long.parseLong(accessSuccessCount));
        statAccessService.saveOrUpdateStatAccess(stat);
    }
}
